﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using RuoVea.DynamicWebApi;
using RuoVea.ExDto;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.OmiApi.Log.Entitys;
using RuoVea.OmiApi.Log.Service.Dto;
using System.ComponentModel;

namespace RuoVea.OmiApi.Log.Service;

/// <summary>
/// 异常日志服务 🔷
/// </summary>
[ApiExplorerSettings(GroupName = "system")]
public class SysLogExService : IApplicationService
{
    private readonly SugarRepository<SysLogEx> _thisRepository;

    /// <summary>
    /// 异常日志服务
    /// </summary>
    /// <param name="thisRepository"></param>
    public SysLogExService(SugarRepository<SysLogEx> thisRepository) => _thisRepository = thisRepository;

    /// <summary>
    /// 分页查询异常日志🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<PageResult<SysLogExDto>> GetPagesAsync([FromQuery] SysLogExParam data)
    {
        DateTime? endTime = data.EndTime;
        if (endTime.HasValue)
        {
            endTime = endTime.Value.Date.AddDays(1).AddSeconds(-1);
        }
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(data.Name?.Trim()), u => u.Name.Contains(data.Name.Trim()))
            .WhereIF(!string.IsNullOrEmpty(data.ClassName?.Trim()), u => u.ClassName.Contains(data.ClassName.Trim()))
            .WhereIF(!string.IsNullOrEmpty(data.MethodName?.Trim()), u => u.MethodName.Contains(data.MethodName.Trim()))
            .WhereIF(!string.IsNullOrEmpty(data.ExceptionMsg?.Trim()), u => u.ExceptionMsg.Contains(data.ExceptionMsg.Trim()))
            .WhereIF(data.BeginTime.HasValue, u => u.ExceptionTime >= data.BeginTime.Value)
            .WhereIF(endTime.HasValue, u => u.ExceptionTime <= endTime.Value)
            .OrderByDescending(x => x.Id)
            .ToPageAsync<SysLogEx, SysLogExDto>(data.PageNo, data.PageSize);
        return query;
    }

    /// <summary>
    /// 根据主键查询🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<SysLogExDto> GetDataAsync([FromQuery] EntityBaseId data)
    {
        var model = await _thisRepository.GetByIdAsync(data.Id);
        return model.Adapt<SysLogExDto>();
    }
    /// <summary>
    /// 删除指定异常日志🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete]
    public virtual async Task<bool> DeleteDataAsync([FromBody] EntityBaseId data) => await _thisRepository.DeleteAsync(m => data.Id == m.Id);

    /// <summary>
    /// 清空操作日志 🔖
    /// </summary>
    /// <returns></returns>
    [HttpDelete]
    [DisplayName("清空操作日志")]
    public bool Clear()
    {
       return _thisRepository.AsSugarClient().DbMaintenance.TruncateTable<SysLogEx>();
    }
}